<template>
    <div class="c-fieldUpload upload" :disabled="config.disabled">
        <template v-if="this.$refs.upload">
            <div class="upload-list" v-for="(item,index) in this.$refs.upload.fileList" :key="index"
                :style="{backgroundImage: `url(${item.url})`}">
                <template v-if="item.status === 'finished' && item.url">
                    <div class="upload-list-cover" v-if="isPicture(item.url)">
                        <Icon type="ios-eye-outline" @click.native="handleView(item.url)"></Icon>
                        <Icon v-if="!config.disabled" type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                    <div class="upload-list-file" v-else>
                        {{getFileName(item.url)}} 
                        <Icon v-if="!config.disabled" type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                    </div>
                </template>
                <template v-else>
                    <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
            </div>
        </template>
        <Upload ref="upload" type="drag" :show-upload-list="false"
            style="display: inline-block; width: 100%;"
            :default-file-list="defaultList"
            :format="config.format ? config.format.split(',') : pictureList"
            :accept="config.accept || '.jpg,.jpeg,.png'"
            :max-size="config.maxSize || 10240"
            :multiple="config.multiple"
            :action="config.action || (baseUrl + '/file/uploadFile')"
            :data="config.data || null"
            :name="config.name || 'file'"
            :on-success="change"
            :on-format-error="handleFormatError"
            :on-exceeded-size="handleMaxSize"
            :disabled="config.disabled"
        >
            <div style="width: 56px;height:56px;line-height:56px;">
                <Icon type="ios-camera" size="20"></Icon>
            </div>
        </Upload>
        <Modal v-model="visible" footer-hide>
            <img :src="imgName" v-if="visible" style="width: 100%">
        </Modal>
    </div>
</template>

<script>
import Setting from '@/setting.js'

export default {
    props: {
        value: {
            type: String,
            default: null
        },
        config: {
            default() {
                return {}
            }
        }
    },
    data() {
        return {
            defaultList: [],
            imgName: '',
            visible: false,
            // baseUrl: 'http://8.136.98.216:10001/tz',
            baseUrl: Setting.apiBaseURL + '/tz',
            pictureList: ['jpg', 'jpeg', 'png']
        }
    },
    watch: {
        value: {
            handler(val) {
                // val = "http://8.136.98.216:10001/tz/FILE/20230714/node3.png"
                this.defaultList = val ? [{ name: 'name', url: val }] : []
            },
            immediate: true
        },
    },
    methods: {
        change(res, file) {
            let data = file.response.data
            let url = file.url
            let newData = {}

            try {
                if (!file.url && data) {
                    if (data.url) {
                        url = data.url
                    } else if (data.newFileName) {
                        url = this.baseUrl + data.newFileName.replace(/^./, '')
                    }
                    file.url = url
                }
                let arr = url ? url.split('/').slice(-1) : ['']
                arr = arr[0].split('.') || []
                newData = {
                    url,
                    fileName: data.fileName,
                    title: arr[0],
                    extendName: arr[1],
                }
                console.log("file: part-upload.vue:95  change  newData:", newData,file)
                this.$emit('change', url, newData)
            } catch (error) {
                this.$emit('change', url, newData)
            }
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleRemove(file) {
            this.$refs.upload.fileList = []
            this.$emit('change', '', {})
        },
        handleFormatError(file) {
            this.$Notice.warning({
                desc: 'File format is incorrect, please select jpg or png.'
            });
        },
        handleMaxSize(file) {
            this.$Notice.warning({
                desc: 'File is too large, no more than 2M.'
            });
        },
        getFileName(url) {
            let arr = url.split('/')
            if (arr.length) {
                return arr.slice(-1)[0]
            } else {
                url
            }
        },
        isPicture(url) {
            if (!url) {
                return false
            }
            try {
                let arr = url.match(/\.([^.])+$/g)
                let suffix = arr.length ? arr[0].replace('.', '') : url

                return this.pictureList.includes(suffix)
            } catch (error) {
                return false
            }
        }
    },
    mounted() {
    }
}
</script>

<style lang="less" scoped>
.upload {
    position: relative;
    min-width: 60px;
    height: 60px;
    border: 1px solid transparent;
    border-radius: 4px;
    overflow: hidden;
    &:has(.upload-list-file) {
        background: #fdfdfd;
        border: 1px solid #dcdee2;
        // height: 32px;
        // .upload-list {
        //     line-height: 32px;
        // }
    }
}
.upload-list {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    line-height: 60px;
    text-align: center;
    overflow: hidden;
    background: #fff;
    background-position: center;
    background-size: contain;
    background-repeat: no-repeat;
    z-index: 1;
}

.upload-list img {
    width: 100%;
    height: 100%;
}

.upload-list-cover {
    display: none;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background: rgba(0, 0, 0, .6);
}

.upload-list:hover .upload-list-cover {
    display: block;
}

.upload-list-file i {
    font-size: 20px;
    margin-left: 8px;
    color: red;
    cursor: pointer;
}
.upload-list-cover i {
    font-size: 20px;
    margin: 0 2px;
    color: #fff;
    cursor: pointer;
}
</style>